package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.commen.ReturnSuccess;
import com.itheima.dto.PageComDto;
import com.itheima.pojo.SubjectsDirectorys;
import com.itheima.service.SubjectsDirectorysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author Gongjx
 * @date 2022/1/10
 */
@RestController
@RequestMapping("/directorys")
public class DirectorysController {
    @Autowired
    private SubjectsDirectorysService subjectsDirectorysService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 目录修改
     */
    @PutMapping("/{id}")
    public ReturnSuccess update(@RequestBody SubjectsDirectorys subjectsDirectorys){
        subjectsDirectorysService.updateById(subjectsDirectorys);
        return ReturnSuccess.success();
    }
    /**
     * 目录列表
     */
    @GetMapping
    public PageComDto findPage(Integer page,Integer pagesize,Integer subjectID,String directoryName,Integer state){
        return subjectsDirectorysService.findPage(page,pagesize,subjectID,directoryName,state);
    }

    /**
     * 目录删除
     */
    @DeleteMapping("/{id}")
    public ReturnSuccess delete(@PathVariable Integer id){
        subjectsDirectorysService.removeById(id);
        return ReturnSuccess.success();
    }
    /**
     * 目录添加
     */
    @PostMapping
    public Integer add(@RequestBody SubjectsDirectorys subjectsDirectorys){
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        String jsonString = JSON.toJSONString(userId);
        Integer uid = JSON.parseObject(jsonString, Integer.class);
        subjectsDirectorys.setCreatorID(uid);
        subjectsDirectorys.setAddDate(new Date());
        subjectsDirectorys.setTotals(0);
        subjectsDirectorys.setState(1);
        subjectsDirectorysService.save(subjectsDirectorys);
        return subjectsDirectorys.getId();
    }
    /**
     * 目录状态
     */
    @PostMapping("/{id}/{state}")
    public ReturnSuccess updateByStats(@PathVariable Integer id,@PathVariable  Integer state){
        LambdaUpdateWrapper<SubjectsDirectorys> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SubjectsDirectorys::getId,id).set(SubjectsDirectorys::getState,state);
        subjectsDirectorysService.update(wrapper);
        return ReturnSuccess.success();
    }
    /**
     * 目录详情
     */
    @GetMapping("/{id}")
    public SubjectsDirectorys findById(@PathVariable Integer id){
        SubjectsDirectorys subjectsDirectorys = subjectsDirectorysService.getById(id);
        return subjectsDirectorys;
    }
}
